import rrd_base
import re
import time

import snmp
import color

try:
    from pyrrd.rrd import DataSource, RRA, RRD
    from pyrrd.graph import DEF, CDEF, VDEF
    from pyrrd.graph import LINE, AREA, GPRINT
    from pyrrd.graph import ColorAttributes, Graph
except:
    print "Couldn't load required modules. You probably need to install it with:"
    sys.exit('sudo apt-get install python-pyrrd python-pysnmp4')

class RrdUptime(rrd_base.RrdBase):
    def __init__(self, domain):
        super(RrdUptime,self).__init__(domain=domain, group="cpu", instance="uptime")

    def create_file(self):
        dataSources = []
        dataSources.append(DataSource( dsName='uptime', dsType='GAUGE', heartbeat=self.heartbeat()))

        roundRobinArchives = []
        for func in ['AVERAGE', 'MAX', 'MIN']:
            for step,row in self.rra_pattern():
                roundRobinArchives.append(RRA(cf=func, xff=0.5, steps=step, rows=row))

        self.myRRD = RRD(self.filename, ds=dataSources, rra=roundRobinArchives, step=self.data_step())
        self.myRRD.create()

    def graph(self):
        d = DEF(rrdfile=self.myRRD.filename, vname='d', dsName='uptime', cdef="MAX")
        c = CDEF(vname="days", rpn="{0},86400,/".format(d.vname))
        v = VDEF(vname='v', rpn="{0},MAXIMUM".format(c.vname))
        a = AREA(defObj=c, color=color.RGBA['green'])
        l = LINE(2, defObj=v, color=color.RGBA['black'], legend="Peak")
        p = GPRINT(v, "%.1lf%s Days")

        for tf in self.graph_time_frames().keys():
            g = Graph(self.image_name(tf),
                      start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                      lower_limit=0.000001,
                      title='"Uptime for {0} - Updated {1}"'.format(self.data_domain, time.strftime("%Y%m%d at %H:%M")),
                      vertical_label='Days',
                      height=self.graph_height, width=self.graph_width,
                      x_grid=self.grid[tf],
                      step=self.graph_step_times[tf])
            g.data.extend([d ,c ,v ,a , l, p])
            g.write()

            if False:
                g = Graph(self.icon_name(tf),
                          start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                          lower_limit=0.000001,
                          no_legend=True,
                          height=self.icon_height, width=self.icon_width,
                          step=self.graph_step_times[tf])
                g.data.extend([d ,c ,a])
                g.write()

class RrdUptimeLocal(RrdUptime):
    def __init__(self, domain):
        super(RrdUptimeLocal,self).__init__(domain=domain)

    def update(self):
        f = open("/proc/uptime")
        for line in f:
            words = line.split()
            self.myRRD.bufferValue(int(round(time.time())), words[0])
            self.myRRD.update()

class RrdUptimeSnmp(RrdUptime):
    def __init__(self, domain):
        super(RrdUptimeSnmp,self).__init__(domain=domain)

    def update(self):
        upt = snmp.get((1,3,6,1,2,1,1,3,0))
        self.myRRD.bufferValue(int(round(time.time())), float(upt)/100.0)
        self.myRRD.update()
